//
//  PlantDetailTableViewController.m
//  yilutongxing
//
//  Created by ios-21 on 17/4/28.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "DataUtils.h"
#import "PlantDetailTableViewController.h"
#import "PlantDetailTableViewCell.h"
#import "PlantDetailContentTableViewCell.h"
#import "YZEDrugplanModel.h"
#import "TheraTitleCell.h"
#import "TheraMedicineTitleCell.h"
#import "TheraTakeplanCell.h"
#import "NextCheckItemView.h"
#import "RPNextCheckItem.h"
#import "PhotosView.h"

#define URL_AcceptDrugplan @"/api/drugplans/accept/"
#define URL_GetDrugplan @"/api/drugplans/"

#define THERATITLECELL @"thera_title_cell"
#define THERAMEDICINECELL @"thera_medicine_cell"
#define THERATAKEPLANCELL @"thera_takeplan_cell"

@implementation MedicineRowModel
@end

@interface PlantDetailTableViewController ()
@property (nonatomic, retain) UIButton *btn_accept;
@property (nonatomic, strong) NSString *dateRange;//日期范围
@property (nonatomic, strong) NSMutableArray *nextCheckItems;
@property (nonatomic, strong) NSDictionary *medicineRowDic;//药品名称行号及药品名称
@property (nonatomic, strong) NSMutableArray *medicineRowArr;//药品行数据数组
@property (nonatomic, strong) PhotosView *pview;
@property (nonatomic, strong) NextCheckItemView *nv;//因为这个界面只会产生一个NextCheckItemView实例，所以可以让这个类持有
@end

@implementation PlantDetailTableViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
//解决tabbar push 后下面的白条的问题
    UIView *contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT+self.tabBarController.tabBar.frame.size.height);
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"用药方案";
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PlantDetailTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TheraTitleCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:THERATITLECELL];
    [self.tableView registerNib:[UINib nibWithNibName:@"TheraMedicineTitleCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:THERAMEDICINECELL];
    [self.tableView registerNib:[UINib nibWithNibName:@"TheraTakeplanCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:THERATAKEPLANCELL];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //self.tableView.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20); 
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    [self genMedicinePlans];
    [self genNextCheckItemView];
    [self.tableView reloadData];
    //[self setFooterView];
}
- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setFooterView{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 85)];
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH-40, 40)];
    //按钮文案及状态
    NSString *title = @"接受建议";
    UIColor *color = [UIColor colorWithRed:55/255.0 green:147/255.0 blue:235/255.0 alpha:1];
    if (self.drugplan.accept==1) {
        title = @"已接受";
        color = [UIColor lightGrayColor];
    }
    else {
        [btn addTarget:self action:@selector(acceptAction) forControlEvents:UIControlEventTouchUpInside];
    }
    [btn setTitle:title forState:UIControlStateNormal];
    btn.layer.cornerRadius = 20;
    btn.layer.masksToBounds = YES;
    btn.backgroundColor = color;
    view.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1];
    [view addSubview:btn];
    self.btn_accept = btn;
    self.tableView.tableFooterView = view;
}
-(void)acceptAction{
    NSLog(@"接受建议");
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingFormat:@"%@%ld?%@", URL_AcceptDrugplan, [self.drugplan.id longValue], PLATFORM] parameters:nil delegate:self requestTag:4 successBlock:^(id responseObject) {
        [self.btn_accept setTitle:@"已接受" forState:UIControlStateNormal];
        [self.btn_accept setBackgroundColor:[UIColor grayColor]];
        [self.btn_accept removeTarget:self action:@selector(acceptAction) forControlEvents:UIControlEventTouchUpInside];
    }];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    /*
    switch (section) {
        case 0:
            return self.medicineRowArr.count + 2;
        default:
            return 2;
    }
     */
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.pview) {
        [self.pview removeFromSuperview];
    }
    /*
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            PlantDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            cell.sectionNameLable.text = @"用药方案";
            return cell;
        } else if(indexPath.row==1){
            TheraTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:THERATITLECELL forIndexPath:indexPath];
            [cell setConstraintsForType:1];
            [cell.btn_add setHidden:YES];
            [cell.btn_modify setHidden:YES];
            [cell.under_line setHidden:YES];
            cell.title.text = self.dateRange?self.dateRange:@"无";
            return cell;
        } else{
            NSUInteger index = indexPath.row - 2;
            MedicineRowModel *m = self.medicineRowArr[index];
            if (self.medicineRowDic[[NSNumber numberWithUnsignedInteger:index]]) {
                TheraMedicineTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:THERAMEDICINECELL forIndexPath:indexPath];
                [cell setConstraintsForType:1];
                cell.medcine_name.text = m.name;
                cell.take_count.text = m.frequncy;
                return cell;
            }
            else {
                TheraTakeplanCell *cell = [tableView dequeueReusableCellWithIdentifier:THERATAKEPLANCELL forIndexPath:indexPath];
                [cell setConstraintsForType:1];
                cell.time_index.text = m.takeCount;
                cell.take_time.text = m.takeTime;
                cell.dose.text = m.takeDose;
                cell.unit.text = m.takeUnit;
                return cell;
            }
        }
    }else   */
    if (indexPath.section == 0){
        if (indexPath.row == 0) {
            PlantDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            cell.sectionNameLable.text = @"下次检查时间";
            return cell;
        }else{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"systemCell1"];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"systemCell1"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.textLabel.textColor = [UIColor colorWithRed:128/255.0 green:128/255.0 blue:128/255.0 alpha:1];
            }
            cell.textLabel.text = self.drugplan.nextchecktime;
            
            return cell;
        }
        
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            PlantDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            cell.sectionNameLable.text = @"下次检查项目";
            return cell;
        }else{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"checkitemcell"];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"checkitemcell"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                [cell.contentView addSubview:self.nv];
            }
            return cell;
        }
    /*}else if (indexPath.section == 3){
        if (indexPath.row == 0) {
            PlantDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            cell.sectionNameLable.text = @"检查报告";
            
            return cell;
        }else{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"systemCell"];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"systemCell"];
                cell.textLabel.textColor = [UIColor colorWithRed:128/255.0 green:128/255.0 blue:128/255.0 alpha:1];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.textLabel.text = @"暂无";
            
            return cell;
        }*/
    }else{
        if (indexPath.row == 0) {
            PlantDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            cell.sectionNameLable.text = @"其它建议";
            return cell;
        }else{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"systemCell2"];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"systemCell2"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            if (!self.pview && self.drugplan.imageurls.length>0) {
                NSArray *urlArr = [DataUtils getTidyArrayFromString:self.drugplan.imageurls];
                self.pview = [[PhotosView alloc]initWithFrame:CGRectMake(20, 10, tableView.frame.size.width - 40, 100)];
                self.pview.pic_urls = urlArr;
                [cell.contentView addSubview:self.pview];
            }

            return cell;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
    if (indexPath.section==0&&indexPath.row>0) {
        return 38;
    } else  */
    if(indexPath.section==1 && indexPath.row>0){
        return self.nv.height;
    } else if(indexPath.section==2 && indexPath.row>0){
        return 120;
    }else{
        return 40;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 15;
    }else{
        return 9.9;
    }
}

#pragma mark - 业务逻辑
/*
 生成下次检查项目UI
 */
-(void)genNextCheckItemView{
    //整理下次检查项目数据
    self.nextCheckItems = [NSMutableArray array];
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
    NSArray *indicators_sorted = [self.drugplan.specialIndicatorsList sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        RPNextCheckItem *l = obj1;
        RPNextCheckItem *r = obj2;
        NSInteger li = [DataUtils getIndicatorSortNumber:l.name];
        NSInteger ri = [DataUtils getIndicatorSortNumber:r.name];
        return li>ri;
    }];
    for (int i=0; i<indicators_sorted.count; i++) {
        RPNextCheckItem *item = (RPNextCheckItem*)indicators_sorted[i];
        RPNextCheckItem *parent = item.parent;
        NSString *parentName = @"\t";
        if (parent && parent.name) {
            parentName = parent.name;
        }
        if (dic1[parentName]) {
            [dic1[parentName] addObject:item.name];
        }
        else {
            dic1[parentName] = [NSMutableArray array];
            [dic1[parentName] addObject:item.name];
        }
    }
    NSArray *parent_name_arr = [dic1 allKeys];
    
    for (int j=0; j<parent_name_arr.count; j++) {
        NSString *parent_name = parent_name_arr[j];
        NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:dic1[parent_name], @"subitems", parent_name, @"item_type", nil];
        [self.nextCheckItems addObject:item];
    }
    self.nv = [[NextCheckItemView alloc]initWithData: self.nextCheckItems];
}

/*
 整理药品处方数据
 */
-(void)genMedicinePlans{
    NSUInteger rowNumber = 0;
    NSMutableDictionary *tdic = [NSMutableDictionary dictionary];
    NSEnumerator *en1 = [self.drugplan.medicines reverseObjectEnumerator];
    SingleMedicine *medicine = nil;
    while (medicine = [en1 nextObject]) {
        NSString *startime = @"无";
        if (medicine.startTime) {
            startime = [medicine.startTime stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
        }
        NSString *endtime = @"至今";
        if (medicine.endTime) {
            endtime = [medicine.endTime stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
        }
        self.dateRange = [NSString stringWithFormat:@"%@-%@", startime, endtime];
        //服药时间
        NSMutableArray *timeArr = [[medicine.times componentsSeparatedByString:@","] mutableCopy];
        NSEnumerator *en2 = [timeArr reverseObjectEnumerator];
        NSString *timeStr = nil;
        while (timeStr = [en2 nextObject]) {
            if (![timeStr isNotEmpty]) {
                [timeArr removeObject:timeStr];
            }
        }
        MedicineRowModel *m = [MedicineRowModel new];
        m.name = medicine.medicineName?medicine.medicineName:@"未知药物";
        m.frequncy = medicine.frequency;
        [self.medicineRowArr addObject:m];
        [tdic setObject:@1 forKey:[NSNumber numberWithUnsignedInteger:rowNumber]];
        rowNumber += timeArr.count + 1;
        
        //剂量
        NSMutableArray *doseArr = [[medicine.dose componentsSeparatedByString:@","] mutableCopy];
        en2 = [doseArr reverseObjectEnumerator];
        NSString *doseStr = nil;
        while (doseStr = [en2 nextObject]) {
            if (![doseStr isNotEmpty]) {
                [doseArr removeObject:doseStr];
            }
        }
        //单位
        NSMutableArray *unitArr = [[medicine.unit componentsSeparatedByString:@","] mutableCopy];
        en2 = [unitArr reverseObjectEnumerator];
        NSString *unitStr = nil;
        while (unitStr = [en2 nextObject]) {
            if (![unitStr isNotEmpty]) {
                [unitArr removeObject:unitStr];
            }
        }
        //放入数组
        for (int i=0; i<timeArr.count; i++) {
            m = [MedicineRowModel new];
            m.takeCount = [NSString stringWithFormat:@"第%@次 ", [DataUtils arabicConvert2Chinese:(i+1)]];
            m.takeTime = timeArr[i];
            if (i<doseArr.count) {
                m.takeDose = doseArr[i];
            }
            else if(doseArr.count==0){
                m.takeDose = @" ";
            }
            else {
                m.takeDose = doseArr[0];
            }
            if (i<unitArr.count) {
                m.takeUnit = unitArr[i];
            }
            else if(unitArr.count==0){
                m.takeUnit = @" ";
            }
            else {
                m.takeUnit = unitArr[0];
            }
            [self.medicineRowArr addObject:m];
        }
    }
    self.medicineRowDic = tdic;
}


#pragma mark - 数据配置
- (NSArray *)medicineRowArr{
    if (!_medicineRowArr) {
        _medicineRowArr = [NSMutableArray array];
    }
    return _medicineRowArr;
}

@end
